package parser;

import lexer.Lexer;

/**
 * 简单的语法分析器
 * Created by weijianyu on 2017/1/12.
 */
public class BasicParser {
    private Lexer lexer;
    private boolean isLegalStatement = true;

    public BasicParser(Lexer lexer) {
        this.lexer = lexer;
    }

    public void statements() {
        // statements -> expression; | expression; statements

        expression();

        //继续读取下一个字符
        if (lexer.match(Lexer.SEMI)) {
            // 如果下一个字符不是EOI 采用右边的解析方法
            lexer.advance();
        } else {
            // 如果不以;结束，语法错误
            isLegalStatement = false;
            System.out.println("line: " + lexer.yylineno + " Missing semicolon");
            return;
        }
        if (!lexer.match(Lexer.EOI)) {
            // 不结束还有字符
            statements();
        }
        if (isLegalStatement) {
            System.out.println("The statement is legal");
        }
    }

    private void expression() {
        // expression -> term expression'
        term();
        expr_prime();   // expression'
    }

    private void expr_prime() {
        // expression' -> PLUS term expression' | '空'
        if (lexer.match(Lexer.PLUS)) {
            lexer.advance();
            term();
            expr_prime();
        } else if (lexer.match(Lexer.UNKNOWN_SYMBOL)) {
            isLegalStatement = false;
            System.out.println("unknow symbol: " + lexer.yytext);
            return ;
        } else {
            // '空' 不解析 直接返回
        }
    }

    private void term() {
        // term -> factor term'
        factor();
        term_prime();   // term'
    }

    private void term_prime() {
        // term' -> TIMES factor term' | '空'
        if (lexer.match(lexer.TIMES)) {
            lexer.advance();
            factor();
            term_prime();
        } else {
            // 不以*开头执行空
        }
    }

    private void factor() {
        // factor -> NUM_OR_ID | LP expression RP

        if (lexer.match(Lexer.NUM_OR_ID)) {
            lexer.advance();
        } else if (lexer.match(Lexer.LP)) {
            lexer.advance();
            expression();
            if (lexer.match(Lexer.RP)) {
                lexer.advance();
            } else {
                //有左括号但没有右括号，错误
                isLegalStatement = false;
                System.out.println("line: " + lexer.yylineno + " Missing )");
                return;
            }
        } else {
            // 这里不是数字，解析出错
            isLegalStatement = false;
            System.out.println("illegal statements");
            return;
        }
    }

    public static void main(String[] args) {
        Lexer lexer = new Lexer();
        BasicParser basic_parser = new BasicParser(lexer);
        basic_parser.statements();
    }
}
